﻿package com.vincce.sport.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.ExcelUtil;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.entity.CompetitionGroup;
import com.vincce.sport.entity.CompetitionSeason;
import com.vincce.sport.entity.CompetitionTeam;
import com.vincce.sport.entity.PreliminaryContest;
import com.vincce.sport.entity.School;
import com.vincce.sport.mapper.CompetitionGroupMapper;
import com.vincce.sport.mapper.CompetitionSeasonMapper;
import com.vincce.sport.mapper.CompetitionTeamMapper;
import com.vincce.sport.mapper.PreliminaryContestMapper;
import com.vincce.sport.mapper.SchoolMapper;

@Controller
@RequestMapping("/preliminaryContest")
public class PreliminaryContestController extends BaseController{

	@Resource
	private PreliminaryContestMapper preliminaryContestMapper;
	
	@Resource
	private CompetitionTeamMapper competitionTeamMapper;
	
	@Resource
	private CompetitionGroupMapper competitionGroupMapper;
	
	@Resource
	private CompetitionSeasonMapper competitionSeasonMapper;
	
	@Resource
	private SchoolMapper schoolMapper;
	
	@RequestMapping("/list")
	public String list(Model model, PreliminaryContest preliminaryContest){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("seasonId", preliminaryContest.getSeasonId());
		param.put("type", preliminaryContest.getType());
		List<PreliminaryContest> preliminaryContestList = preliminaryContestMapper.findPreliminaryContestList(param);
		if(preliminaryContest.getType().equals(2)){
			param.clear();
			param.put("type", 1);
			param.put("seasonId", preliminaryContest.getSeasonId());
			List<CompetitionTeam> competitionTeamList = competitionTeamMapper.findCompetitionTeamList(param);		//取小组第一名
			CompetitionSeason competitionSeason = competitionSeasonMapper.findCompetitionSeasonById(preliminaryContest.getSeasonId());
			String eliminateImg = competitionSeason.getEliminateImg();
			if(!CheckUtil.isEmpty(eliminateImg)){
				competitionSeason.setEliminateImg(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+eliminateImg, "ori"));
			}


			model.addAttribute("eliminateImg", competitionSeason.getEliminateImg());
			model.addAttribute("competitionTeamList", competitionTeamList);
		}else{
			List<CompetitionGroup> competitionGroupList = competitionGroupMapper.findCompetitionGroupList(param);
			for(CompetitionGroup competitionGroup : competitionGroupList){
				param.clear();
				param.put("groupId", competitionGroup.getId());
				List<CompetitionTeam> competitionTeamList = competitionTeamMapper.findCompetitionTeamList(param);
				for(int i = 0; i < competitionTeamList.size(); i++){
					CompetitionTeam competitionTeam = competitionTeamList.get(i);
					switch (competitionTeam.getNumber()) {
					case 1:
						competitionGroup.setCompetitionTeam(competitionTeam);
						break;
					case 2:
						competitionGroup.setCompetitionTeam2(competitionTeam);
						break;
					case 3:
						competitionGroup.setCompetitionTeam3(competitionTeam);
						break;
					
					default:
						competitionGroup.setCompetitionTeam4(competitionTeam);
						break;
					}
				}
				competitionGroup.setCompetitionTeamList(competitionTeamList);
			}
			model.addAttribute("competitionGroupList", competitionGroupList);
		}
		List<School> schoolList = schoolMapper.queryBySchoolAll();
		model.addAttribute("preliminaryContest", preliminaryContest);
		model.addAttribute("preliminaryContestList", preliminaryContestList);
		model.addAttribute("schoolList", schoolList);
		return "/backstage/preliminaryContestList";
	}
	
	@RequestMapping("/insertOrUpdate")
	@ResponseBody
	public String insertOrUpdate(Model model, PreliminaryContest preliminaryContest,HttpServletRequest request) throws ParseException{
		String date = request.getParameter("date");
		preliminaryContest.setDate(date);
		Long userId = getCurrentUser().getId();
		Long id = 0L;
		if(CheckUtil.isEmpty(preliminaryContest.getId())){
			preliminaryContest.setCreateTime(new Date());
			preliminaryContest.setCreateUser(userId);
			preliminaryContestMapper.insert(preliminaryContest);
			id = preliminaryContest.getId();
		}else{
			preliminaryContest.setUpdateTime(new Date());
			preliminaryContest.setUpdateUser(userId);
			id = preliminaryContestMapper.update(preliminaryContest);
		}
		return JSON.toJSONString(id);
	}
	
	@RequestMapping("/queryContestById")
	@ResponseBody
	public String queryContestById(HttpServletRequest request, Long id){
		PreliminaryContest preliminaryContest = preliminaryContestMapper.findPreliminaryContestById(id);
		return JSON.toJSONString(preliminaryContest);
	}
	
	@RequestMapping("/querySchoolAll")
	@ResponseBody
	public String querySchoolAll(){
		List<School> schoolList = schoolMapper.queryBySchoolAll();
		return JSON.toJSONString(schoolList);
	}
	
	@RequestMapping("/importContest")
	@ResponseBody
	public void importContest(HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "file", required = false) MultipartFile file){
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		Long seasonId = Long.valueOf(request.getParameter("seasonId"));
//		Boolean flag = false;
		if(file !=null && !file.isEmpty()){
			Long userId = getCurrentUser().getId();
			try {
				String fileName = file.getOriginalFilename();
				String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
				if(!fileType.equals(".xls")){
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("msg", "格式不正确，只能为.xls的格式");
					map.put("suc", false);
					result.add(map);
				}
				else{
					InputStream in=file.getInputStream();
					POIFSFileSystem poifsFileSystem = new POIFSFileSystem(in);
					HSSFWorkbook workbook = new HSSFWorkbook(poifsFileSystem);
					HSSFSheet aSheet = workbook.getSheetAt(0);
					for(int i=1; i<=aSheet.getLastRowNum();i++){
						HSSFRow aRow = aSheet.getRow(i);
						String date = ExcelUtil.getCellValue(aRow.getCell(0));
						String time = ExcelUtil.getCellValue(aRow.getCell(1));
						String teamName = ExcelUtil.getCellValue(aRow.getCell(2));
						String teamTwoName = ExcelUtil.getCellValue(aRow.getCell(3));
						String schoolName = ExcelUtil.getCellValue(aRow.getCell(4));
						String site = ExcelUtil.getCellValue(aRow.getCell(5));
						
						if(date == null || date.equals("") || time == null || time.equals("")
								|| teamName == null || teamName.equals("") || teamTwoName == null || teamTwoName.equals("")
								|| schoolName == null || schoolName.equals("") || site == null || site.equals("")){
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("msg", "第"+i+"条数据缺失");
							map.put("suc", false);
							result.add(map);
							continue;
						}
						if(teamName.equals(teamTwoName)){
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("msg", "第"+i+"条对阵球队不能相同");
							map.put("suc", false);
							result.add(map);
							continue;
						}
						Map<String, Object> param = new HashMap<String, Object>();
						param.put("seasonId", seasonId);
						param.put("teamName", teamName);
						List<CompetitionTeam> competitionTeamList = competitionTeamMapper.findCompetitionTeamList(param);
						if(!CheckUtil.isEmpty(competitionTeamList)){
							Long teamId = competitionTeamList.get(0).getTeamId();
							
							param.put("teamName", teamTwoName);
							List<CompetitionTeam> competitionTeamList2 = competitionTeamMapper.findCompetitionTeamList(param);
							if(!CheckUtil.isEmpty(competitionTeamList2)){
								Long teamIdTwo = competitionTeamList2.get(0).getTeamId();
								param.clear();
								param.put("name", schoolName);
								List<School> schoolList = schoolMapper.querySchoolList(param);
								if(CheckUtil.isEmpty(schoolList)){
									Map<String, Object> map = new HashMap<String, Object>();
									map.put("msg", "第"+i+"条数据校区不正确");
									map.put("suc", false);
									result.add(map);
									continue;
								}
								Long schoolId = Long.valueOf(schoolList.get(0).getId());
								PreliminaryContest preliminaryContest = new PreliminaryContest();
								preliminaryContest.setSeasonId(seasonId);
								preliminaryContest.setSchoolId(schoolId);
								preliminaryContest.setTeamId(teamId);
								preliminaryContest.setTeamIdTwo(teamIdTwo);
								preliminaryContest.setDate(date);
								preliminaryContest.setTime(time);
								preliminaryContest.setSite(site);
								preliminaryContest.setType(1);
								preliminaryContest.setCreateTime(new Date());
								preliminaryContest.setCreateUser(userId);
								preliminaryContestMapper.insert(preliminaryContest);
							}else{
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("msg", "第"+i+"条数据对阵球队2名称不正确");
								map.put("suc", false);
								result.add(map);
							}
						}else{
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("msg", "第"+i+"条数据对阵球队1名称不正确");
							map.put("suc", false);
							result.add(map);
						}
					}
				}
			} catch (Exception e) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("msg", "导入失败!");
				map.put("suc", false);
				result.add(map);
				e.printStackTrace();
			}
		}else{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("msg", "文件为空!");
			map.put("suc", false);
			result.add(map);
		}
		
		HSSFWorkbook wb = new HSSFWorkbook();//表格
        ExcelUtil.createImportResult(wb, "importResult",result);
        String filename = "importResult"+".xls";
        response.setContentType("application/binary; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + new String(filename.toString().getBytes("UTF-8"), "iso8859-1")
                    + "\"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
//            PrintWriter out = response.getWriter();
//            out.write("<script languge='javascript'>alert('导入成功'); window.location.href='/competitionTeam/list.htm?seasonId="+seasonId+"'</script>");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//        return JSON.toJSONString(flag);
	}
	
	@RequestMapping("/createContestTable")
    public void createContestTable(HttpServletResponse response,HttpServletRequest request){
		HSSFWorkbook wb = new HSSFWorkbook();//表格
        ExcelUtil.createContestTable(wb, "contestTable");
        String filename = "createContestTable"+".xls";
        response.setContentType("application/binary; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + new String(filename.toString().getBytes("UTF-8"), "iso8859-1")
                    + "\"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
	
	@RequestMapping("/deleteEliminateImg")
	@ResponseBody
	public String deleteEliminateImg(HttpServletRequest request,Long seasonId){
		Long count = competitionSeasonMapper.deleteEliminateImg(seasonId);
		return JSON.toJSONString(count > 0);
	}
	
	@RequestMapping("/uploadEliminateImg")
	@ResponseBody
	public String uploadEliminateImg(@RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request) throws IOException{
		Long seasonId = Long.valueOf(request.getParameter("seasonId"));
		Boolean flag = false;
		String msg = "";
        Map<String, Object> result = new HashMap<String, Object>();
        SimpleStorageClient.StorageResult obj = new SimpleStorageClient.StorageResult(200, "");
        if (file != null && !file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
                msg = "格式不正确,只支持后缀名为.jpg或者.png的图片上传。";
            } else {
                obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
                if (obj.statusCode == 200) {
                	String path = obj.info.replaceAll("\\\\", "/");
                	CompetitionSeason competitionSeason = new CompetitionSeason();
                	competitionSeason.setId(seasonId);
                	competitionSeason.setEliminateImg(path);
                	Long count = competitionSeasonMapper.update(competitionSeason);
                	flag = count > 0;
                }
            }
        } else{
        	msg = "请选择图片!";
        }
        result.put("suc", flag);
        result.put("msg", msg);
        return JSON.toJSONString(result);
	}
}
